﻿using System;
using YWM.Common.Exceptions;

namespace PLCWpfTest.Common
{
    public class RelayCommand : BaseCommand
    {
        private event Action<object> _executing;
        public event Action<object> Executing
        {
            add { _executing += value; }
            remove { _executing -= value; }
        }

        private event Action<FriendlyException> _unexecutedFriendlyException;
        public event Action<FriendlyException> UnexecutedFriendlyException
        {
            add { _unexecutedFriendlyException += value; }
            remove { _unexecutedFriendlyException -= value; }
        }

        protected override void OnExecute(object parameter)
        {
            if (_executing != null)
            {
                try
                {
                    IsExecuting = true;
                    _executing(parameter);
                }
                catch (FriendlyException ex)
                {
                    _unexecutedFriendlyException?.Invoke(ex);
                }
                finally
                {
                    IsExecuting = false;
                }
            }
        }
    }

    public class RelayCommand<TResult> : BaseCommand
    {
        private event Func<object, (TResult, DatabaseMethod)> _executing;
        public event Func<object, (TResult, DatabaseMethod)> Executing
        {
            add { _executing += value; }
            remove { _executing -= value; }
        }

        private event Action<FriendlyException> _unexecutedFriendlyException;
        public event Action<FriendlyException> UnexecutedFriendlyException
        {
            add { _unexecutedFriendlyException += value; }
            remove { _unexecutedFriendlyException -= value; }
        }

        protected override void OnExecute(object parameter)
        {
            if (_executing != null)
            {
                try
                {
                    IsExecuting = true;
                    (TResult, DatabaseMethod) result = _executing(parameter);
                }
                catch (FriendlyException ex)
                {
                    _unexecutedFriendlyException?.Invoke(ex);
                }
                finally
                {
                    IsExecuting = false;
                }
            }
        }
    }
}
